import {Button, Dialog, Spinner} from '@kintone/kintone-ui-component/esm/js';
import './desktop.css';
import {ErrorHandler} from '../common/ErrorHandler';
import * as tyc from '../api/TianyanchaAPI';
import * as qcc from '../api/QichachaAPI';
import util from '../common/util';

((PLUGIN_ID) => {
  'use strict';

  kintone.events.on('app.record.detail.show', (event) => {
    const config = kintone.plugin.app.getConfig(PLUGIN_ID);
    if (!('apiServer' in config)) {
      return;
    }

    const server = [tyc.SERVER, qcc.SERVER].find(v => v.ID === config.apiServer);
    if (!server) {
      return;
    }

    const record = event.record;

    const companyField = `${server.ID}_companyField` in config ? config[`${server.ID}_companyField`] : '';
    if (util.isEmptyString(companyField)) {
      return;
    }

    const companyName = record[companyField].value;
    if (util.isEmptyString(companyName)) {
      return;
    }

    const errorHandler = new ErrorHandler();
    const spinner = new Spinner();
    kintone.app.record.getHeaderMenuSpaceElement().appendChild(spinner.render());

    // create the search button
    const companyEl = kintone.app.record.getFieldElement(companyField);
    const button = new Button({text: '查询公司信息', type: 'submit'});
    companyEl.appendChild(button.render());
    companyEl.style.cssText = 'display: flex;';
    companyEl.getElementsByClassName('kuc-btn')[0].style.cssText = 'min-width: 130px;margin-left: 20px';
    button.on('click', () => {
      const p = document.createElement('p');
      p.innerHTML = `确定要查询 "${companyName}" 的信息吗？<br><br>`;
      p.innerHTML += `查询会调用${server.NAME}API，并产生一定的费用！`;
      p.innerHTML += `${server.ID}_apiCost` in config && !util.isEmptyString(config[`${server.ID}_apiCost`]) ?
        '<br>单次收费: ' + config[`${server.ID}_apiCost`] + '元' : '';
      confirmDialog.setContent(p);
      confirmDialog.show();
    });


    const setCompanyInfoToKintone = (result) => {
      const body = {
        app: event.appId,
        id: record.$id.value,
        record: {}
      };
      for (const key in result) {
        if (!result.hasOwnProperty(key)
          || !(`${server.ID}_${key}` in config)
          || !config[`${server.ID}_${key}`]
        ) {
          continue;
        }
        body.record[config[`${server.ID}_${key}`]] = {value: result[key]};
      }
      return kintone.api(kintone.api.url('/k/v1/record', true), 'PUT', body);
    };

    const searchButton = new Button({text: '确定', type: 'submit'});
    const cancelButton = new Button({text: '取消', type: 'normal'});
    const confirmDialogFooter = document.createElement('div');
    confirmDialogFooter.appendChild(searchButton.render());
    confirmDialogFooter.appendChild(cancelButton.render());
    confirmDialogFooter.className = 'confirm-dialog-footer';
    const confirmDialog = new Dialog({
      header: '',
      footer: confirmDialogFooter,
      isVisible: false,
      showCloseButton: true
    });
    kintone.app.record.getHeaderMenuSpaceElement().appendChild(confirmDialog.render());
    cancelButton.on('click', () => {
      confirmDialog.hide();
    });
    searchButton.on('click', () => {
      confirmDialog.hide();
      spinner.show();

      const getCompanyInfo = () => {
        let apiServer;
        switch (server.ID) {
          case tyc.SERVER.ID:
            apiServer = new tyc.TianyanchaAPI(PLUGIN_ID);
            return apiServer.getBaseInfo({keyword: companyName});
          case qcc.SERVER.ID:
            apiServer = new qcc.QichachaAPI(PLUGIN_ID, config[`${qcc.SERVER.ID}_authKey`], config[`${qcc.SERVER.ID}_secretKey`]);
            return apiServer.getBasicDetailsByName({keyword: companyName});
          default:
            return kintone.Promise.resolve();
        }
      };

      getCompanyInfo().then(result => {
        return setCompanyInfoToKintone(result);
      }).then(() => {
        spinner.hide();
        window.location.reload();
      }).catch(e => {
        spinner.hide();
        errorHandler.throwError(e, server.NAME);
      });
    });
  });
})(kintone.$PLUGIN_ID);